package com.zx.flow.core.execute.eventhandler;

import com.google.common.collect.Lists;
import com.zx.flow.api.config.FlowConfig;
import com.zx.flow.api.dict.FlowDict.Status;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.request.FlowParamCreate;
import com.zx.flow.api.execute.response.FlowResult;
import com.zx.flow.api.util.AssertUtil;
import com.zx.flow.core.execute.EventHandler;
import java.util.Date;
import java.util.UUID;

/**
 * 事件处理器【创建流程】
 */
public class EventFlowCreateHandler extends EventHandler<FlowParamCreate> {

    @Override
    public boolean in(FlowContext flow, FlowParamCreate param) {
        return flow == null;
    }

    @Override
    public FlowResult on(FlowContext flow, FlowParamCreate param) {

        FlowConfig config = this.getFlowConfig(param.getFlowCode(), null);
        AssertUtil.checkNotNull(config, "流程配置不存在, flowCode=" + param.getFlowCode());

        flow = new FlowContext();
        String uuid = UUID.randomUUID().toString();
        flow.setId(uuid);
        flow.setTitle(param.getTitle());
        flow.setFlowConfigId(config.getId());
        flow.setFlowConfigCode(config.getFlowCode());
        flow.setStatus(Status.flowNew);
        flow.setStartDateTime(null);
        flow.setEndDateTime(null);
        String extendData = param.getExtendData();
        if (extendData == null) {
            flow.setExtendData("{}");
        } else {
            flow.setExtendData(extendData);
        }
        flow.setApplyReason(param.getApplyReason());
        flow.setApplyAccountCode(param.getApplyAccountCode());
        flow.setCreateTime(new Date());
        flow.setUpdateTime(new Date());
        flow.setCurrentNodeCode("");
        flow.setNodes(Lists.newArrayList());
        flow.setParentFlowId("");
        flow.setParentNodeId("");
        // 保存流程数据
        this.saveFlow(flow);

        return FlowResult.ok(flow);
    }
}
